package com.xh.bussiness.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.course.bean.request.PrepareConfigGroupRequest;
import com.xh.bussiness.course.model.Course;
import com.xh.bussiness.course.model.PrepareConfigGroup;
import com.xh.bussiness.course.model.PrepareConfigGroupUser;
import com.xh.bussiness.permission.bean.request.QueryUserRequest;
import com.xh.bussiness.permission.model.User;
import com.xh.bussiness.permission.service.IUserService;
import com.xh.bussiness.system.bean.request.GlobalPrepareConfigGroupRequest;
import com.xh.bussiness.system.model.GlobalPrepareConfigGroup;
import com.xh.bussiness.system.dao.GlobalPrepareConfigGroupMapper;
import com.xh.bussiness.system.model.GlobalPrepareConfigGroupUser;
import com.xh.bussiness.system.model.UserDataPermission;
import com.xh.bussiness.system.service.IGlobalPrepareConfigGroupService;
import com.xh.bussiness.system.service.IGlobalPrepareConfigGroupUserService;
import com.xh.core.service.impl.BaseServiceImpl;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.xh.core.bean.XhPage;
import com.xh.core.util.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Jqm
 * @since 2021-02-05
 */
@Service
public class GlobalPrepareConfigGroupServiceImpl extends BaseServiceImpl<GlobalPrepareConfigGroupMapper, GlobalPrepareConfigGroup> implements IGlobalPrepareConfigGroupService {

    @Autowired
    private IUserService userService;
    @Autowired
    private IGlobalPrepareConfigGroupUserService globalPrepareConfigGroupUserService;

    @Override
    public XhPage queryGlobalPrepareConfigGroupPage(XhPage page, GlobalPrepareConfigGroupRequest bean) {
        QueryWrapper qw = new QueryWrapper<GlobalPrepareConfigGroup>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page, qw);
    }

    @Override
    public List queryGlobalPrepareConfigGroup(GlobalPrepareConfigGroupRequest bean) {
        QueryWrapper qw = new QueryWrapper<GlobalPrepareConfigGroup>();
        //拼装条件
        qw = prepareParams(bean, qw);

        List<GlobalPrepareConfigGroup> list = this.dao.selectList(qw);
        QueryWrapper<User> userQuery = new QueryWrapper<>();
        userQuery.eq("sys_user", 1);
        List<User> users = userService.queryByCondition(userQuery);
        if (users.isEmpty()) {
            return list;
        }
        Integer userCount = users.size();
        GlobalPrepareConfigGroup defualtGroup = null;
        for (GlobalPrepareConfigGroup globalPrepareConfigGroup : list) {
            if (globalPrepareConfigGroup.getId().equals("0")) {
                defualtGroup = globalPrepareConfigGroup;
            } else {
                userCount = userCount - (globalPrepareConfigGroup.getUserCount() == null ? 0 : globalPrepareConfigGroup.getUserCount());
            }
        }
        if (defualtGroup != null) {
            defualtGroup.setUserCount(userCount);
        }
        return list;
    }

    @Override
    public GlobalPrepareConfigGroup queryByUserId(String userId) {
        return super.dao.queryByUserId(userId);
    }

    @Override
    public void deleteByGroupId(String id) {
        this.dao.deleteByGroupId(id);
        // 删除该组下的所有用户
        globalPrepareConfigGroupUserService.deleteByGroupId(id);
    }

    @Override
    public XhPage queryUsersByGroupId(XhPage page, String groupId, String userName) {

        // 默认组，查询所有没有分组的教师，要根据教师的权限查询（学科、班型）
        List<String> userIds = new ArrayList<>();
        if ("0".equals(groupId)) {
            List<User> users = userService.queryAll();
            userIds = users.stream().map(User::getId).collect(Collectors.toList());
            List<GlobalPrepareConfigGroupUser> groupUsers = globalPrepareConfigGroupUserService.queryByCondition(new QueryWrapper<>());
            if (!CollectionUtils.isEmpty(groupUsers)) {
                List<String> otherUserIds = groupUsers.stream().map(GlobalPrepareConfigGroupUser::getUserId).collect(Collectors.toList());
                userIds.removeAll(otherUserIds);
            }
        } else {
            QueryWrapper<GlobalPrepareConfigGroupUser> qw = new QueryWrapper<>();
            qw.eq("group_id", groupId);
            List<GlobalPrepareConfigGroupUser> list = globalPrepareConfigGroupUserService.queryByCondition(qw);
            userIds = list.stream().map(GlobalPrepareConfigGroupUser::getUserId).collect(Collectors.toList());
        }
        if (userIds.size() == 0) {
            page.setRecords(new ArrayList());
            return page;
        }
        QueryUserRequest bean = new QueryUserRequest();
        bean.setUserIds(userIds);
        if (StringUtils.isNotEmpty(userName)) {
            bean.setUsername(userName);
        }
        return userService.queryUserPage(page, bean);
    }

    @Override
    public String changeUserGroup(GlobalPrepareConfigGroupRequest bean) {
        // 先删除原先的数据
//        QueryWrapper<GlobalPrepareConfigGroupUser> qw = new QueryWrapper();
//        qw.eq("group_id", bean.getGroupId());
//        globalPrepareConfigGroupUserService.deleteByCondition(qw);
        if (CollectionUtils.isEmpty(bean.getUserIds())) {
            return null;
        }
        QueryWrapper<GlobalPrepareConfigGroupUser> qw = new QueryWrapper();
        qw.eq("user_id", bean.getUserIds().get(0));
        GlobalPrepareConfigGroupUser globalPrepareConfigGroupUser = globalPrepareConfigGroupUserService.selectFirst(qw);
        if (globalPrepareConfigGroupUser != null) {
            GlobalPrepareConfigGroup globalPrepareConfigGroup = super.getById(globalPrepareConfigGroupUser.getGroupId());
            globalPrepareConfigGroup.setUserCount(globalPrepareConfigGroup.getUserCount() == null ? 0 : (globalPrepareConfigGroup.getUserCount() - bean.getUserIds().size()) > 0 ? globalPrepareConfigGroup.getUserCount() - bean.getUserIds().size() : 0);
            super.update(globalPrepareConfigGroup);
        }
        // 默认组 单独处理
        if ("0".equals(bean.getGroupId())) {
            for (String userId : bean.getUserIds()) {
                // 删除用户原先所在分组（物理删除）
                globalPrepareConfigGroupUserService.deleteByUserId(userId);
            }
            return "换组成功";
        }
        for (String userId : bean.getUserIds()) {
            // 删除用户原先所在分组（物理删除）
            globalPrepareConfigGroupUserService.deleteByUserId(userId);
            GlobalPrepareConfigGroupUser prepareConfigGroupUser = new GlobalPrepareConfigGroupUser();
            prepareConfigGroupUser.setGroupId(bean.getGroupId());
            prepareConfigGroupUser.setUserId(userId);
            globalPrepareConfigGroupUserService.insert(prepareConfigGroupUser);
        }
        // 更新组的用户数
        qw = new QueryWrapper();
        qw.eq("group_id", bean.getGroupId());
        Integer count = globalPrepareConfigGroupUserService.selectCount(qw);

        GlobalPrepareConfigGroup prepareConfigGroup = new GlobalPrepareConfigGroup();
        prepareConfigGroup.setId(bean.getGroupId());
        prepareConfigGroup.setUserCount(count);
        super.update(prepareConfigGroup);
        return "换组成功";
    }

    @Override
    public XhPage queryUsers(XhPage page, String courseId, String userName) {
        QueryUserRequest bean = new QueryUserRequest();
        bean.setUsername(userName);
        page = userService.queryUserPage(page, bean);

        List<GlobalPrepareConfigGroupUser> groupUsers = globalPrepareConfigGroupUserService.queryAll();

        List<GlobalPrepareConfigGroup> groups = super.queryAll();
        List<Map<String, Object>> list = page.getRecords();

        // 设置用户的组名称
        for (Map<String, Object> map : list) {
            String userId = MapUtils.getString(map, "id");
            for (GlobalPrepareConfigGroupUser groupUser : groupUsers) {
                if (groupUser.getUserId().equals(userId)) {
                    for (GlobalPrepareConfigGroup group : groups) {
                        if (groupUser.getGroupId().equals(group.getId())) {
                            map.put("groupName", group.getName());
                        }
                        break;
                    }
                    break;
                }
            }
            // 没有组的为默认组
            if (map.get("groupName") == null) {
                map.put("groupName", "默认组");
            }
        }
        return page;
    }

    @Override
    public String getUserPrepareConfig(String userId) {
        QueryWrapper<GlobalPrepareConfigGroupUser> qw = new QueryWrapper<>();
        qw.eq("user_id", userId);
        GlobalPrepareConfigGroupUser globalPrepareConfigGroupUser = globalPrepareConfigGroupUserService.selectFirst(qw);
        GlobalPrepareConfigGroup globalPrepareConfigGroup = null;
        if (globalPrepareConfigGroupUser != null) {
            globalPrepareConfigGroup = super.getById(globalPrepareConfigGroupUser.getGroupId());
        } else {
            globalPrepareConfigGroup = super.getById("0");
        }
        return globalPrepareConfigGroup.getConfig();
    }


    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(GlobalPrepareConfigGroupRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        if (bean.getDefaulted() != null) {
            qw.eq("defaulted", bean.getDefaulted());
        }
        return qw;
    }
}
